import CryptoJS from 'crypto-js'

// 数据加密
export function encryption(params) {
  let { data, type, param, key } = params
  const result = JSON.parse(JSON.stringify(data))
  if (type === 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele])
    })
  } else {
    param.forEach(ele => {
      const data = result[ele]
      key = CryptoJS.enc.Latin1.parse(key)
      const iv = key
      // 加密
      const encrypted = CryptoJS.AES.encrypt(data, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
      })
      result[ele] = encrypted.toString()
    })
  }
  return result
}

// 第三方登录
export function thirdPartyLogin(provider) {
  return new Promise((resolve, reject) => {
    uni.login({
      provider,
      success: (loginRes) => {
        resolve(loginRes)
      },
      fail: (err) => {
        if (err.code === -2 || err.code === -100) {
          this.toast('取消登录')
        }
        reject(err)
      }
    })
  })
}
